import React, { useEffect, useState } from 'react';
import {
  Card,
  Typography,
  Form,
  Input,
  Select,
  Switch,
  Button,
  Upload,
  DatePicker,
  InputNumber,
  Space,
  message,
  Row,
  Col,
  Image
} from 'antd';
import {
  UploadOutlined,
  SaveOutlined,
  ArrowLeftOutlined
} from '@ant-design/icons';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import { useNavigate } from 'react-router-dom';
import bannerService, { CreateBannerData } from '../../services/banner.service';
import dayjs from 'dayjs';

const { Title } = Typography;
const { Option } = Select;
const { TextArea } = Input;
const { RangePicker } = DatePicker;

const BannerCreate: React.FC = () => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>('');

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '轮播图管理', path: '/banners' },
      { title: '轮播图列表', path: '/banners' },
      { title: '添加轮播图' },
    ]));
  }, [dispatch]);

  // 处理图片上传
  const handleImageUpload = async (file: File) => {
    try {
      const result = await bannerService.uploadImage(file);
      setImageUrl(result.url);
      form.setFieldsValue({ image: result.url });
      message.success('图片上传成功');
      return false; // 阻止默认上传行为
    } catch (error) {
      message.error('图片上传失败');
      return false;
    }
  };

  // 提交表单
  const handleSubmit = async (values: any) => {
    try {
      setLoading(true);

      const submitData: CreateBannerData = {
        title: values.title,
        image: values.image,
        link: values.link || '',
        linkType: values.linkType || 'none',
        linkTarget: values.linkTarget || '',
        order: values.order || 0,
        isActive: values.isActive !== false,
        startDate: values.dateRange?.[0]?.toISOString(),
        endDate: values.dateRange?.[1]?.toISOString(),
        description: values.description || '',
        platform: values.platform || 'all'
      };

      await bannerService.createBanner(submitData);
      message.success('轮播图创建成功');
      navigate('/banners');
    } catch (error) {
      message.error('创建失败，请重试');
      console.error('创建轮播图失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 上传前验证
  const beforeUpload = (file: File) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只能上传 JPG/PNG 格式的图片!');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB!');
      return false;
    }
    return true;
  };

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate('/banners')}
          style={{ marginRight: 16 }}
        >
          返回列表
        </Button>
        <Title level={2} style={{ display: 'inline-block', margin: 0 }}>
          添加轮播图
        </Title>
      </div>

      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            isActive: true,
            platform: 'all',
            linkType: 'none',
            order: 0
          }}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label="轮播图标题"
                name="title"
                rules={[
                  { required: true, message: '请输入轮播图标题' },
                  { max: 100, message: '标题长度不能超过100个字符' }
                ]}
              >
                <Input placeholder="请输入轮播图标题" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="平台类型"
                name="platform"
                rules={[{ required: true, message: '请选择平台类型' }]}
              >
                <Select placeholder="请选择平台类型">
                  <Option value="mobile">移动端</Option>
                  <Option value="web">Web端</Option>
                  <Option value="all">全平台</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                label="轮播图图片"
                name="image"
                rules={[{ required: true, message: '请上传轮播图图片' }]}
              >
                <div>
                  <Upload
                    name="image"
                    listType="picture-card"
                    showUploadList={false}
                    beforeUpload={beforeUpload}
                    customRequest={({ file }) => handleImageUpload(file as File)}
                  >
                    {imageUrl ? (
                      <Image
                        src={imageUrl}
                        alt="轮播图"
                        style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                      />
                    ) : (
                      <div>
                        <UploadOutlined />
                        <div style={{ marginTop: 8 }}>上传图片</div>
                      </div>
                    )}
                  </Upload>
                  <div style={{ marginTop: 8, color: '#666', fontSize: '12px' }}>
                    建议尺寸：800x400px，支持JPG、PNG格式，大小不超过2MB
                  </div>
                </div>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="描述" name="description">
                <TextArea
                  rows={4}
                  placeholder="请输入轮播图描述"
                  maxLength={500}
                  showCount
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={8}>
              <Form.Item label="链接类型" name="linkType">
                <Select placeholder="请选择链接类型">
                  <Option value="none">无链接</Option>
                  <Option value="product">商品链接</Option>
                  <Option value="category">分类链接</Option>
                  <Option value="shop">店铺链接</Option>
                  <Option value="external">外部链接</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="链接地址" name="link">
                <Input placeholder="请输入链接地址" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="链接目标" name="linkTarget">
                <Input placeholder="请输入链接目标ID或URL" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={8}>
              <Form.Item label="排序值" name="order">
                <InputNumber
                  min={0}
                  placeholder="排序值，数字越小越靠前"
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="显示时间" name="dateRange">
                <RangePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder={['开始时间', '结束时间']}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="状态" name="isActive" valuePropName="checked">
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                icon={<SaveOutlined />}
              >
                保存轮播图
              </Button>
              <Button onClick={() => navigate('/banners')}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default BannerCreate;
